package cn.edu.sctu.sctu_lysd.view.act;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.JsonBaseBeen;
import cn.edu.sctu.sctu_lysd.bean.UserProfile;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.databinding.ActivityUpdateUserInfoBinding;
import cn.edu.sctu.sctu_lysd.net.NetService;
import cn.edu.sctu.sctu_lysd.net.RetrofitHelper;
import cn.edu.sctu.sctu_lysd.utils.CompressImgUtil;
import cn.edu.sctu.sctu_lysd.utils.ImageLoader;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wangfuxin on 2017-04-26.
 */

public class UpdateUserInfoAct extends BaseActivity {

    private ActivityUpdateUserInfoBinding mBinding;

    public final static int PHOTO_REQUEST_CODE = 6689;

    private NetService service;

    private String imgPath = "";

    private SharePreferenceUtils sharePreferenceUtils;

    private CompressImgUtil compressImgUtil;

    private ProgressUtil progressUtil;

    private ProgressDialog progressDialog;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_update_user_info;
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityUpdateUserInfoBinding) bind;

        sharePreferenceUtils = SharePreferenceUtils.getInstance(this);

        compressImgUtil = CompressImgUtil.getInstance();

        progressUtil = ProgressUtil.getInstance(this);

        mBinding.selectPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(UpdateUserInfoAct.this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(UpdateUserInfoAct.this, permissions, 321);
                } else {
                    Intent intent = new Intent(UpdateUserInfoAct.this, PhotoActivity.class);

                    startActivityForResult(intent, PHOTO_REQUEST_CODE);
                }

            }
        });

        mBinding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, false, "loding");

                upload();
            }
        });

        mBinding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        L.e("path", resultCode + "-------" + requestCode);

        if (resultCode == RESULT_OK && requestCode == PHOTO_REQUEST_CODE) {

            Bundle bundle = data.getExtras();
            ArrayList<String> stringArray = bundle.getStringArrayList(PhotoActivity.IMAGE_PATH_INTENT_FLAG);

            imgPath = stringArray.get(0);

            ImageLoader.getInstance().loadImage(stringArray.get(0), mBinding.userImg, false);

        }

    }


    private void upload() {

        try {


            Data data = initData();


            RetrofitHelper helper = RetrofitHelper.getInstance();

            service = (NetService) helper.getService(NetService.class);

            UUID uuid = UUID.randomUUID();
            String fileName = uuid + ".jpeg";

            /**
             * 压缩处理
             */
            compressImgUtil.compressImageByScale(data.imgPath, CacheKeyConfig.CACHE_HOME, fileName);


            final RequestBody requestBody =
                    RequestBody.create(MediaType.parse("multipart/form-data"), new File(CacheKeyConfig.CACHE_HOME + "/" + fileName));

            Call<JsonBaseBeen<UserProfile>> call = service.updateUserInfo(sharePreferenceUtils.getString(CacheKeyConfig.CACHE_ACCESS_TOKEN),
                    data.nickname, data.alipayNumber, requestBody);


            call.enqueue(new Callback<JsonBaseBeen<UserProfile>>() {
                @Override
                public void onResponse(Call<JsonBaseBeen<UserProfile>> call, Response<JsonBaseBeen<UserProfile>> response) {
                    compressImgUtil.recursionDeleteFile(new File(CacheKeyConfig.CACHE_HOME));

                    progressUtil.dismiss(progressDialog);

                    if (response.code() == 200 && response.body().getMeta().getCode() == 200) {

                        UserProfile userProfile = response.body().getData();

                        sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_NICKNAME, userProfile.getNickname());
                        sharePreferenceUtils.setCache(CacheKeyConfig.CACHE_USER_AVATAR_URL, userProfile.getAvatarUrl());

                        JumpUtils.jumpActivity(UpdateUserInfoAct.this, IndexActivity.class);

                    } else {

                        Toast.makeText(UpdateUserInfoAct.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                }

                @Override
                public void onFailure(Call<JsonBaseBeen<UserProfile>> call, Throwable t) {
                    compressImgUtil.recursionDeleteFile(new File(CacheKeyConfig.CACHE_HOME));

                    progressUtil.dismiss(progressDialog);
                    Toast.makeText(UpdateUserInfoAct.this, "网络错误", Toast.LENGTH_LONG).show();
                }
            });


        } catch (MyException e) {
            e.printStackTrace();
            Toast.makeText(UpdateUserInfoAct.this, e.getMessage(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();


        }

    }

    private Data initData() throws MyException {

        String nickname = mBinding.nicknameEdit.getText().toString();
        String alipayNumber = mBinding.aliPayNumberEdit.getText().toString();

        if (imgPath.equals("")) throw new MyException("请选择图片");
        if (nickname.equals("")) throw new MyException("请输入昵称");
        if (alipayNumber.equals("")) throw new MyException("请选择图片");

        return new Data(imgPath, nickname, alipayNumber);
    }


    class MyException extends Exception {

        public MyException(String message) {
            super(message);
        }
    }

    class Data {

        public String imgPath, nickname, alipayNumber;

        public Data(String imgPath, String nickname, String alipayNumber) {
            this.imgPath = imgPath;
            this.nickname = nickname;
            this.alipayNumber = alipayNumber;
        }
    }

}
